package com.njxxted.activiti.common.intercept;

import com.njxxted.activiti.common.constant.Constant;
import com.njxxted.activiti.common.exception.CustomerException;
import com.njxxted.activiti.common.response.ResponseVo;
import com.njxxted.activiti.common.util.FeignUtil;
import com.njxxted.activiti.common.util.HttpContextUtil;
import com.njxxted.activiti.common.util.JsonUtils;
import com.njxxted.activiti.common.util.StringUtils;
import com.njxxted.activiti.modules.api.PermissionApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 描述：自定义请求拦截器
 * <p>
 * 作者：HuTongFu
 * 时间：2019/7/12 10:37
 */
@Component
public class SysInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //如果false，停止流程，api被拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //判断请求类型，是否是ajax请求或者来自浏览器的请求，如果是则直接放过，否则进行token验证
        if (HttpContextUtil.isAjax(request)  || !HttpContextUtil.isFromBrowse(request)) {
            return true;
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            String requestURI = request.getRequestURI();
            logger.info("requestURI:{}", requestURI);
            this.response401(response, request.getRequestURI());
            return false;
        }
        //调用服务进行验证
        PermissionApi api = new FeignUtil<PermissionApi>().invokeService(PermissionApi.class);
        ResponseVo responseVo = api.validToken(authorization);
        if (Constant.Permission.SUCCESS == Integer.parseInt(responseVo.get("code").toString())) {
            return true;
        } else {
            this.response401(response, request.getRequestURI());
            logger.debug("验证结果：{}", responseVo.get("msg"));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void response401(HttpServletResponse response, String uri) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            ResponseVo resVo = new ResponseVo(Constant.Permission.UN_LOGIN, "无权访问(Unauthorized):" + uri);
            String data = JsonUtils.beanToJson(resVo);
            out.append(data);
        } catch (IOException e) {
            throw new CustomerException("直接返回Response信息出现IOException异常:", e);
        }
    }
}
